#!/bin/bash
#author: xieziqiang
#email: xie.zi.qiang@outlook.com

# https://zookeeper.apache.org/doc/current/zookeeperStarted.html#sc_Download
set -e
#****** vars *********#
ZK_VERSION="3.9.2"
ZK_INSTALL_PATH="/usr/local"
JAVA_HOME="/usr/local/jdk"
#****** functions *********#
color() {
    local message="$1"
    local status="$2"
    local terminal_width
    terminal_width=$(tput cols)
    local middle_column=$(( terminal_width / 2))
    local SETCOLOR_SUCCESS="\033[1;32m"  # 绿色
    local SETCOLOR_FAILURE="\033[1;31m"  # 红色
    local SETCOLOR_WARNING="\033[1;33m"  # 黄色
    local SETCOLOR_NORMAL="\033[0m"      # 重置颜色
    printf '%s\n\033[%sG' "${message}"  "${middle_column}"
    # Print the status message
    printf "["
    case ${status} in
        success|0)
            echo -en  "${SETCOLOR_SUCCESS}  OK  "
            ;;
        failure|1)
            echo -en  "${SETCOLOR_FAILURE}FAILED"
            ;;
        *)
            echo -en "${SETCOLOR_WARNING}WARNING"
            ;;
    esac
    echo -e "${SETCOLOR_NORMAL}]"
}

judge_current_user () {
    if [ "$(id -u)" = "0" ];then
        color "current user is administrator" 0
    else
        color "current user is not administrator" 1
        exit
    fi
}

judge_java_env () {
    if ${JAVA_HOME}/bin/java -version &> /dev/null;then
        color "java env is existed" 0
    else
        color "java env is not existed!" 1
        exit
    fi
}


process_file () {
    if [ ! -e "apache-zookeeper-${ZK_VERSION}-bin.tar.gz" ];then
        color "current directory dont exist apache-zookeeper-${ZK_VERSION}-bin.tar.gz" 1
        exit
    else
        tar -xvf "apache-zookeeper-${ZK_VERSION}-bin.tar.gz" -C "${ZK_INSTALL_PATH}"
        ln -s "${ZK_INSTALL_PATH}/apache-zookeeper-${ZK_VERSION}-bin" "${ZK_INSTALL_PATH}/zookeeper"
        echo "PATH=${ZK_INSTALL_PATH}/zookeeper/bin:\$PATH" > /etc/profile.d/zookeeper.sh
        cp -b ${ZK_INSTALL_PATH}/zookeeper/conf/zoo_sample.cfg ${ZK_INSTALL_PATH}/zookeeper/conf/zoo.cfg
        cat > /lib/systemd/system/zookeeper.service <<EOF
[Unit]
Description=zookeerper.service,version ${ZK_VERSION}
After=network.target
[Service]
Type=forking
Environment=JAVA_HOME=${JAVA_HOME}
ExecStart=${ZK_INSTALL_PATH}/zookeeper/bin/zkServer.sh start
ExecStop=${ZK_INSTALL_PATH}/zookeeper/bin/zkServer.sh stop
[Install]
WantedBy=multi-user.target
EOF
        systemctl daemon-reload
        systemctl enable zookeeper
        systemctl start zookeeper && color "zookeeper start success" 0 || color "zookeeper start failed !" 1
    fi
} 

main () {
    judge_current_user
    judge_java_env
    process_file
}

main